package com.leetcode.array;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 890. 查找和替换模式 Find and Replace Pattern
 *
 * @ClassName FindReplacePattern
 * @Description 我是一个注释
 * @Author HaiziGe
 * @Date 2018/11/9 13:47
 * @Version 1.0
 **/
public class FindReplacePattern {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> result  = new ArrayList<>();

        char[] patternChars = pattern.toCharArray();
        for (String word : words) {
            if (match(word, patternChars)) {
                result.add(word);
            }
        }

        return result;
    }

    private boolean match(String word, char[] patternChars) {

        char[] wordChars = word.toCharArray();
        Map<Character, Character> index = new HashMap<>();

        for (int i = 0; i < wordChars.length; i++) {
            if (index.containsKey(wordChars[i]) && patternChars[i] != index.get(wordChars[i])) {
                return false;
            } else if (!index.containsKey(wordChars[i]) && index.containsValue(patternChars[i])) {
                return false;
            } else {
                index.put(wordChars[i], patternChars[i]);
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String[] words = {"abc","deq","mee","aqq","dkd","ccc"};
        List<String> abb = new FindReplacePattern().findAndReplacePattern(words, "abb");

        for (String s : abb) {
            System.out.println(s);
        }

    }

}
